﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.WindowsAzure.StorageClient;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.ServiceRuntime;
using System.Collections.Specialized;

namespace Helpers
{
    public static class StorageHelper
    {
        //For first usage to create the container!
        public static void EnsureContainerExists()
        {
            var container = GetContainer();
            container.CreateIfNotExist();

            var permissions = container.GetPermissions();
            permissions.PublicAccess = BlobContainerPublicAccessType.Container;
            container.SetPermissions(permissions);
        }

        //To get the container!
        public static CloudBlobContainer GetContainer()
        {
            // Get a handle on account, create a blob service client and get container proxy
            var account = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
            var client = account.CreateCloudBlobClient();

            return client.GetContainerReference(RoleEnvironment.GetConfigurationSettingValue("ContainerName"));
        }

        public static void SaveImage(string id, string name, string description, string tags, string fileName, string contentType, byte[] data)
        {
            // Create a blob in container and upload image bytes to it
            var blob = GetContainer().GetBlobReference(name);

            blob.Properties.ContentType = contentType;

            // Create some metadata for this image
            var metadata = new NameValueCollection();
            metadata["Id"] = id;
            metadata["Filename"] = fileName;
            metadata["ImageName"] = String.IsNullOrEmpty(name) ? "unknown" : name;
            metadata["Description"] = String.IsNullOrEmpty(description) ? "unknown" : description;
            metadata["Tags"] = String.IsNullOrEmpty(tags) ? "unknown" : tags;

            // Add and commit metadata to blob
            blob.Metadata.Add(metadata);
            blob.UploadByteArray(data);
        }

    }
}
